{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import time\n",
    "start_time =time.time()\n",
    "import requests\n",
    "\n",
    "requests.get('http://192.168.2.44:7000/api/status')\n",
    "import pydicom as dicom\n",
    "from itertools import chain\n",
    "import os\n",
    "from bmmodule.utils import get_required_parameters\n",
    "from bmutils.pipelines import SortSeriesByOrientation,AdjustProtocolForOrientation\n",
    "from copy import deepcopy\n",
    "from bmutils.utils import npy2str, str2npy, flatten\n",
    "\n",
    "from brain_ctp.ctp_api import CTPModel\n",
    "from bmutils.series import generate_series,SeriesClass\n",
    "#from bmutils.pipelines import *\n",
    "\n",
    "CTP_folder = '/Resources//Biomind_CTP_01_/'\n",
    "#ctp_studies=[]\n",
    "#for x in os.listdir(CTP_folder):\n",
    "#    ctp_studies.append(os.path.join(CTP_folder,x))\n",
    "#ctp_studies\n",
    "ctp_series = [list(chain.from_iterable(list(generate_series(CTP_folder).values())))][0]\n",
    "#all_ctp_series\n",
    "tensorrt_server = \"http://192.168.2.44:7000\"\n",
    "res = CTPModel(tensorrt_server)(ctp_series)\n",
    "end_time =time.time()-start_time"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 62,
   "metadata": {},
   "outputs": [],
   "source": [
    "ctp_series = generate_series(CTP_folder)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 80,
   "metadata": {},
   "outputs": [
    {
     "ename": "NameError",
     "evalue": "name 'payload' is not defined",
     "output_type": "error",
     "traceback": [
      "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
      "\u001b[0;31mNameError\u001b[0m                                 Traceback (most recent call last)",
      "\u001b[0;32m<ipython-input-80-6ce888d8c2fb>\u001b[0m in \u001b[0;36m<module>\u001b[0;34m\u001b[0m\n\u001b[0;32m----> 1\u001b[0;31m \u001b[0mseries\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mseries_classifier\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mmetadata\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mget_required_parameters\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mpayload\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m      2\u001b[0m \u001b[0mctp_volume_uid\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mseries_classifier\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mget\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mSeriesClass\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mCTP\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mkey\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n",
      "\u001b[0;31mNameError\u001b[0m: name 'payload' is not defined"
     ]
    }
   ],
   "source": [
    "series, series_classifier, metadata = get_required_parameters(payload)\n",
    "ctp_volume_uid = series_classifier.get(SeriesClass.CTP.key)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "94.21994018554688"
      ]
     },
     "execution_count": 2,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "end_time"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "import pickle\n",
    "with open(\"/Resources/output_ctp_model.pkl\", \"wb\") as fn:\n",
    "    pickle.dump(res, fn)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 101,
   "metadata": {},
   "outputs": [],
   "source": [
    "import pickle\n",
    "with open(\"/Resources/output_ctp_model.pkl\", \"rb\") as fn:\n",
    "    result = pickle.load(fn)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 118,
   "metadata": {},
   "outputs": [],
   "source": [
    " AIF_phase_time =None\n",
    "AIF_phase_time if AIF_phase_time!=\"None\" else None"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 127,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "1\n"
     ]
    }
   ],
   "source": [
    "a= 1\n",
    "if a:\n",
    "    print(1)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 115,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "1"
      ]
     },
     "execution_count": 115,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "len(result['cache']['M_transform_list'])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 102,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "process_np = np.array(result['cache']['img_sample_list_processed'])\n",
    "#np.array(result['cache']['prepared_data']['img_sample_list_processed']).shape"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 103,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "(16, 32, 512, 512)"
      ]
     },
     "execution_count": 103,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "process_np.shape"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    " for i,x in enumerate(process_np):\n",
    "        print(i)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 104,
   "metadata": {},
   "outputs": [],
   "source": [
    "mismatch_images = [\n",
    "    {\n",
    "        'mask': npy2str(x),  #process_np is 16 x (32,512,512) all data\n",
    "        'scale': (float(np.min(x)), float(np.max(x))),\n",
    "        'png': 'grayscale',\n",
    "        'classification': {f'mismatch_image{i}': 1.0},\n",
    "        'segment_id': f'mismatch_image{i}'\n",
    "    }  for i,x in enumerate(process_np)\n",
    "]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 110,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'mismatch_image0': 1.0}"
      ]
     },
     "execution_count": 110,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "mismatch_images[0]['classification']"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from bmutils.pipelines import AutocastNumpyToJSON\n",
    "result['mip_aif_pos_list'] = AutocastNumpyToJSON()(result['mip_aif_pos_list'])\n",
    "result['mip_vof_pos_list'] = AutocastNumpyToJSON()(result['mip_vof_pos_list'])\n",
    "for x in result['mip_aif_pos_list']:\n",
    "    for y in x:\n",
    "        print(type(y))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "\n",
    "import json\n",
    "for x in result:\n",
    "    print(x)\n",
    "    with open(\"/Resources/model_output.json\", \"w\") as fn:\n",
    "        json.dump(result, fn)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 111,
   "metadata": {},
   "outputs": [],
   "source": [
    "import os,base64\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "for x in res['mip_aif_pos_list']:\n",
    "    for y in x:\n",
    "        print(type(y))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# def recover_seriesuid_instances(series, series_classifier, series_class, metadata):\n",
    "#     if series_class in series_classifier and len(series[series_classifier[series_class]]) > 0:\n",
    "#         series_uid = metadata[series_classifier[series_class]]['SeriesInstanceUID']\n",
    "#         instances = flatten([files for uid, files in series.items() if series_uid in uid])\n",
    "#         return series_uid, instances\n",
    "\n",
    "#     return None, None"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": 69,
   "metadata": {},
   "outputs": [],
   "source": [
    "from bmutils.series import SeriesClass\n",
    "series = generate_series(CTP_folder)\n",
    "# #dicom.read_file(series[0])\n",
    "# #ctp_seriess = list(series.values())[0]\n",
    "# #ctp_series\n",
    "ctp_series_uid=list(series.keys())[0]\n",
    "pay_load={\n",
    "    'pdicom_folder':CTP_folder,\n",
    "    'planguage':'en-us',\n",
    "    'pconfig':{'ctp':{}},\n",
    "    'pseries_classifier':{\n",
    "        SeriesClass.CTP.key:ctp_series_uid\n",
    "    }\n",
    "}\n",
    "series, series_classifier, metadata = get_required_parameters(pay_load)\n",
    "#s=[ generate_series(ctp_study).values() for ctp_study in ['/Resources/CTP/'] ]\n",
    "\n",
    "#ctp_series\n",
    "# series, series_classifier, metadata = get_required_parameters(pay_load)\n",
    "\n",
    "# # get cache data if cache_key is the same\n",
    "\n",
    "# series_by_orientation = deepcopy(SortSeriesByOrientation()(series))\n",
    "ctp_volume_uid = series_classifier.get(SeriesClass.CTP.key)\n",
    "# ctp_series_uid, ctp_instances = recover_seriesuid_instances(series_by_orientation, series_classifier, SeriesClass.CTP.key,\n",
    "#                                                             metadata)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 81,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'1.2.840.113619.2.416.263797347391843930758744724964937820965.35.000000512512.vol<1,16>'"
      ]
     },
     "execution_count": 81,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "ctp_volume_uid"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 87,
   "metadata": {},
   "outputs": [],
   "source": [
    "import copy\n",
    "a = copy.deepcopy(list(series.keys()))\n",
    "del a[a.index(ctp_series_uid)]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 91,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "0 1.2.840.113619.2.416.263797347391843930758744724964937820965.35.000000512512.vol<2,16>\n",
      "1 1.2.840.113619.2.416.263797347391843930758744724964937820965.35.000000512512.vol<3,16>\n",
      "2 1.2.840.113619.2.416.263797347391843930758744724964937820965.35.000000512512.vol<4,16>\n",
      "3 1.2.840.113619.2.416.263797347391843930758744724964937820965.35.000000512512.vol<5,16>\n",
      "4 1.2.840.113619.2.416.263797347391843930758744724964937820965.35.000000512512.vol<6,16>\n",
      "5 1.2.840.113619.2.416.263797347391843930758744724964937820965.35.000000512512.vol<7,16>\n",
      "6 1.2.840.113619.2.416.263797347391843930758744724964937820965.35.000000512512.vol<8,16>\n",
      "7 1.2.840.113619.2.416.263797347391843930758744724964937820965.35.000000512512.vol<9,16>\n",
      "8 1.2.840.113619.2.416.263797347391843930758744724964937820965.35.000000512512.vol<10,16>\n",
      "9 1.2.840.113619.2.416.263797347391843930758744724964937820965.35.000000512512.vol<11,16>\n",
      "10 1.2.840.113619.2.416.263797347391843930758744724964937820965.35.000000512512.vol<12,16>\n",
      "11 1.2.840.113619.2.416.263797347391843930758744724964937820965.35.000000512512.vol<13,16>\n",
      "12 1.2.840.113619.2.416.263797347391843930758744724964937820965.35.000000512512.vol<14,16>\n",
      "13 1.2.840.113619.2.416.263797347391843930758744724964937820965.35.000000512512.vol<15,16>\n",
      "14 1.2.840.113619.2.416.263797347391843930758744724964937820965.35.000000512512.vol<16,16>\n"
     ]
    }
   ],
   "source": [
    "for i,uid in enumerate(a):\n",
    "    print(i,uid)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 89,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "dict_keys(['1.2.840.113619.2.416.263797347391843930758744724964937820965.35.000000512512.vol<1,16>', '1.2.840.113619.2.416.263797347391843930758744724964937820965.35.000000512512.vol<2,16>', '1.2.840.113619.2.416.263797347391843930758744724964937820965.35.000000512512.vol<3,16>', '1.2.840.113619.2.416.263797347391843930758744724964937820965.35.000000512512.vol<4,16>', '1.2.840.113619.2.416.263797347391843930758744724964937820965.35.000000512512.vol<5,16>', '1.2.840.113619.2.416.263797347391843930758744724964937820965.35.000000512512.vol<6,16>', '1.2.840.113619.2.416.263797347391843930758744724964937820965.35.000000512512.vol<7,16>', '1.2.840.113619.2.416.263797347391843930758744724964937820965.35.000000512512.vol<8,16>', '1.2.840.113619.2.416.263797347391843930758744724964937820965.35.000000512512.vol<9,16>', '1.2.840.113619.2.416.263797347391843930758744724964937820965.35.000000512512.vol<10,16>', '1.2.840.113619.2.416.263797347391843930758744724964937820965.35.000000512512.vol<11,16>', '1.2.840.113619.2.416.263797347391843930758744724964937820965.35.000000512512.vol<12,16>', '1.2.840.113619.2.416.263797347391843930758744724964937820965.35.000000512512.vol<13,16>', '1.2.840.113619.2.416.263797347391843930758744724964937820965.35.000000512512.vol<14,16>', '1.2.840.113619.2.416.263797347391843930758744724964937820965.35.000000512512.vol<15,16>', '1.2.840.113619.2.416.263797347391843930758744724964937820965.35.000000512512.vol<16,16>'])"
      ]
     },
     "execution_count": 89,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "series.keys()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# ctp_predict_config = {}\n",
    "# pconfig = pay_load.get('pconfig')\n",
    "# if pconfig:\n",
    "#     ctp_predict_config = pconfig.get('ctp') or pconfig\n",
    "# log.debug(f\"ctp_predict_config: {ctp_predict_config}\")\n",
    "# parameters = OrderedDict({\n",
    "#     'coord_aif': ctp_predict_config.get('coord_aif'),\n",
    "#     'coord_vof': ctp_predict_config.get('coord_vof'),\n",
    "#     'mid_line': ctp_predict_config.get('mid_line')\n",
    "# })"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "for k, v  in res.items():\n",
    "    if type(v) = np.ndarray:\n",
    "        res1.pop(k)\n",
    "        "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def check_type(input):\n",
    "    if type(input) ==list:\n",
    "        for i in input:\n",
    "            check_type(i)\n",
    "    if type(input)==dict:\n",
    "        for k,v in input.items():\n",
    "            check_type(v)\n",
    "    if type(input) in [np.int64, np.int8]:\n",
    "        print(input)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.10"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
